home *** CD-ROM | disk | FTP | other *** search
/ Internet Info 1993 / Internet Info CD-ROM (Walnut Creek) (1993).iso / networking / terms / kermit / b / ckifio.c < prev    next >
Encoding:
C/C++ Source or Header  |  1993-08-06  |  38.1 KB  |  1,310 lines

  1. char *ckzv = "Amiga file support $Id: ckifio.c,v 1.8 93/08/03 08:28:44 swalton Exp Locker: swalton $";
  2.  
  3. /* C K I F I O  --  Kermit file system support for the Amiga */
  4.  
  5. /*
  6.   Author: Frank da Cruz (SY.FDC@CU20B),
  7.   Columbia University Center for Computing Activities, January 1985.
  8.   Modified for Amiga by Jack J. Rouse, The Software Distillery
  9.   Further modified for C Kermit version 4F(095) by Stephen Walton,
  10.   California State University, Northridge, ecphssrw@afws.csun.edu
  11.  
  12.   Copyright (C) 1985, 1992, Trustees of Columbia University in the City of New
  13.   York.  Permission is granted to any individual or institution to use this
  14.   software as long as it is not sold for profit.  This copyright notice must be
  15.   retained.  This software may not be included in commercial products without
  16.   written permission of Columbia University.
  17.  
  18.  $Log:    ckifio.c,v $
  19.  * Revision 1.8  93/08/03  08:28:44  swalton
  20.  * Changed include of SAS and Aztec-specific include files to Amiga
  21.  * standard (clib/ and pragmas/).
  22.  * 
  23.  * Revision 1.7  92/10/30  16:11:42  swalton
  24.  * Added code to call SetCurrentDirName() if and only if ROM version
  25.  * is greater than 37.  Depends on the extern int v37, set in ckitio.c.
  26.  * 
  27.  * Revision 1.6  92/01/15  17:14:16  swalton
  28.  * Delete the Aztec StatToTime function, as it is now identical to the
  29.  * Lattice one.
  30.  * 
  31.  * Also used Id rather than Header in the RCS ID string.
  32.  * 
  33.  * Revision 1.5  91/07/18  16:01:59  swalton
  34.  * zxcmd() fixed to work properly.  I had accidentally copied the first part
  35.  * of the Unix version, which dealt with Kermit sending its received data
  36.  * to a command as its input.  Amiga Kermit doesn't support this, but does
  37.  * support sending the output of a command to a remote Kermit via the
  38.  * pipeopen() routine in ckiutl.c.
  39.  * 
  40.  * Revision 1.4  91/05/29  09:08:17  swalton
  41.  * 1.  Changed function definitions to prototype style.  Required adding
  42.  *     a few forward declarations.
  43.  * 2.  Removed includes of stdio.h, stdlib.h, and string.h, as they are
  44.  *     now pulled in by ckcdeb.h, provided we compile with -DCK_ANSILIBS.
  45.  * 
  46.  * Revision 1.3  90/11/19  21:46:11  swalton
  47.  * Modifications for compiling with SAS/C Version 5.10, courtesy of
  48.  * Larry Rosenman (ler@lerami.lonestar.org, ler on BIX)
  49.  * 
  50.  * Revision 1.2  90/11/07  14:40:57  swalton
  51.  * Version 1.2--released to world as first beta test version simultaneously
  52.  * with release of edit 5A(160).
  53.  * 
  54.  * Revision 1.1  90/07/12  07:56:05  swalton
  55.  * Fairly extensive modifications to bring Amiga Kermit up to Version 5A, edit
  56.  * 149.  Most of the changes can be discerned by reading ckasys.doc, the C Kermit
  57.  * interface document and looking for the items flagged *NEW*.
  58.  * 
  59.  * Revision 1.0  90/04/30  11:54:31  swalton
  60.  * Initial revision
  61.  *  
  62. */
  63.  
  64. /* Includes */
  65.  
  66. #define LONG            /* Prevent LONG definition from coming from
  67.                    ckcdeb.h, as it conflicts with exec/type.h */
  68. #include "ckcdeb.h"        /* Typedefs, formats for debug() */
  69. #undef LONG
  70. #include "ckcker.h"        /* Kermit definitions */
  71. #include "ckcfil.h"        /* File related symbols. */
  72. #if AZTEC_C
  73. #include <stat.h>
  74. #endif
  75. #if __SASC
  76. #include <sys/types.h>
  77. #include <sys/stat.h>
  78. #endif
  79. #include <time.h>
  80. #include <libraries/dosextens.h>
  81. #include <exec/memory.h>
  82.  
  83. #include <clib/exec_protos.h>
  84. #include <clib/dos_protos.h>
  85. #include <pragmas/exec_pragmas.h>
  86. #include <pragmas/dos_pragmas.h>
  87.  
  88. #include <fcntl.h>        /* for prototypes for write() and read() */
  89. #define MAXNAMLEN 30
  90. #ifdef AZTEC_C
  91. char *ckzsys = " Amiga (Aztec C)";
  92. #endif
  93. #ifdef __SASC
  94. char *ckzsys = " Amiga (SAS/C)";
  95. #endif
  96.  
  97. /* Definitions of some Amiga system commands */
  98.  
  99. char *DIRCMD = "list ";            /* For directory listing */
  100. char *DIRCM2 = "list ";            /* Also for directory listing. */
  101. char *DELCMD = "delete ";        /* For file deletion */
  102. char *TYPCMD = "type ";            /* For typing a file */
  103. char *PWDCMD = "cd ";            /* For saying where I am */
  104.  
  105. char *SPACMD = "info ";
  106.  
  107. char *SPACM2 = "info ";            /* should be space in specified directory */
  108.  
  109. char *WHOCMD = "status ";        /* Check process status */
  110.  
  111. #define MAXWLD 300
  112.  
  113. /*
  114.   Functions (n is one of the predefined file numbers from ckermi.h):
  115.  
  116.    zopeni(n,name)   -- Opens an existing file for input.
  117.    zopeno(n,name,attr,fcb)  -- Opens a new file for output.
  118.    zclose(n)        -- Closes a file.
  119.    zchin(n,&c)      -- Gets the next character from an input file.
  120.    zsinl(n,s,x)      -- Reads a line from file number n.
  121.    zsout(n,s)       -- Write a null-terminated string to output file, buffered.
  122.    zsoutl(n,s)      -- Like zsout, but appends a line terminator.
  123.    zsoutx(n,s,x)    -- Write x characters to output file, unbuffered.
  124.    zchout(n,c)      -- Add a character to an output file, unbuffered.
  125.    zchki(name)      -- Check if named file exists and is readable, return size.
  126.    zchko(name)      -- Check if named file can be created.
  127.    zchkspa(fn, len) -- Check if there is enough space for file.
  128.    znewn(name,s)    -- Make a new unique file name based on the given name.
  129.    zdelet(name)     -- Delete the named file.
  130.    zxpand(string)   -- Expands the given wildcard string into a list of files.
  131.    znext(string)    -- Returns the next file from the list in "string".
  132.    zxcmd(n,cmd)     -- Execute the command in a lower fork on file number n.
  133.    zclosf(n)        -- Close input file associated with zxcmd()'s lower fork.
  134.    zrtol(n1,n2)     -- Convert remote filename into local form.
  135.    zltor(n1,n2)     -- Convert local filename into remote form.
  136.    zstrip(n1, n2)   -- Find trailing path component of n1 and return pointer
  137.    zchdir(dirnam)   -- Change working directory.
  138.    zhome()          -- Return pointer to home directory name string.
  139.    zkself()         -- Kill self, log out own job (simply exits)
  140.    zsattr(struct zattr *) -- Return attributes for file which is being sent.
  141.    zstime(f, struct zattr *, x) - Set file creation date from attribute packet.
  142.    zrename(old, new) -- Rename a file.
  143.    zshcmd(s,local)  -- Execute a shell command and redirect its output, if
  144.                        necessary (see ckasys.doc)
  145.   */
  146.  
  147. /* Declarations */
  148.  
  149. FILE *fp[ZNFILS] = {             /* File pointers */
  150.     NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL };
  151.  
  152. /* (PWP) external def. of things used in buffered file input and output */
  153. #ifdef DYNAMIC
  154. extern CHAR *zinbuffer, *zoutbuffer;
  155. #else
  156. extern CHAR zinbuffer[], zoutbuffer[];
  157. #endif /* DYNAMIC */
  158. extern CHAR *zinptr, *zoutptr;
  159. extern int zincnt, zoutcnt;
  160.  
  161. static long iflen = -1;            /* Input file length. */
  162.  
  163. static int fcount;            /* Number of files in wild group */
  164. static char  nambuf[MAXNAMLEN+2];    /* Buffer for a filename */
  165.  
  166. char *mtchs[MAXWLD],        /* Matches found for filename */
  167.      **mtchptr;            /* Pointer to current match */
  168. extern short v37;        /* Are we 2.0 or greater? */
  169.  
  170. /* utility functions from ckiutl.c */
  171. extern int existobj();
  172. struct DirHandle    /* fake structure definition */
  173. {
  174.     int _foo_;
  175. };
  176. extern struct DirHandle *opendir();
  177. extern char *readdir();
  178. void closedir();
  179.  
  180. /*
  181.  * Some new time functions.  These are defined up here to make it obvious
  182.  * that they need changing for your compiler.
  183.  */
  184.  
  185. /*
  186.  * The following uses the fact that, on the Amiga, a tm is a long value
  187.  * containing the number of seconds since midnight January 1, 1970.
  188.  * The Amiga's reference time is January 1, 1978 at midnight.
  189.  * The following conversion value is the number of seconds between
  190.  * those two dates.
  191.  */
  192. #define CONVERT (86400L*(2*366 + 6*365))
  193.  
  194. /*
  195.  * TimeToDateStamp accepts a time_t value as returned by, for instance,
  196.  * time() and converts it into an AmigaDos DateStamp.
  197.  */
  198. static void
  199. TimeToDateStamp(time_t tm, struct DateStamp *ds) {
  200.     long seconds = (long) tm - CONVERT;
  201.     ds->ds_Days = seconds / 86400;
  202.     ds->ds_Minute = (seconds - (ds->ds_Days * 86400)) / 60;
  203.     ds->ds_Tick = TICKS_PER_SECOND * (seconds%60);
  204. }
  205.  
  206. static time_t
  207. StatToTime(long mtime) {
  208.     return((time_t) (mtime + CONVERT));
  209. }
  210.  
  211. /*  Z K S E L F  --  Kill Self: log out own job, if possible.  */
  212. int 
  213. zkself(void) {                /* For "bye", but no guarantee! */
  214.     doexit(GOOD_EXIT, -1);
  215. }
  216.  
  217. /*  Z O P E N I  --  Open an existing file for input. */
  218. int 
  219. zopeni(int n, char *name) {
  220.     debug(F111," zopeni",name,n);
  221.     debug(F101,"  fp","",(int) fp[n]);
  222.     if (chkfn(n) != 0) return(0);
  223.     zincnt = 0;
  224.     if (n == ZSYSFN) {            /* Input from a system function? */
  225. /*** Note, this function should not be called with ZSYSFN ***/
  226. /*** Always call zxcmd() directly, and give it the real file number ***/
  227. /*** you want to use.  ***/
  228.         debug(F110,"zopeni called with ZSYSFN, failing!",name,0);
  229.     *nambuf = '\0';            /* No filename. */
  230.     return(0);            /* fail. */
  231. #ifdef COMMENT
  232.     return(zxcmd(n,name));        /* Try to fork the command */
  233. #endif
  234.     }
  235.     if (n == ZSTDIO) {            /* Standard input? */
  236.     if (isatty(0)) {
  237.         ermsg("Terminal input not allowed");
  238.         debug(F110,"zopeni: attempts input from unredirected stdin","",0);
  239.         return(0);
  240.     }
  241.     fp[ZIFILE] = stdin;
  242.     return(1);
  243.     }
  244.     fp[n] = fopen(name,"r");        /* Real file. */
  245.     debug(F111," zopeni", name, (int) fp[n]);
  246.     if (fp[n] == NULL) perror("zopeni");
  247.     return((fp[n] != NULL) ? 1 : 0);
  248. }
  249.  
  250. /*  Z O P E N O  --  Open a new file for output.  */
  251. int
  252. zopeno(int n, char *name, struct zattr *zz, struct filinfo *fcb) {
  253.  
  254.     char *p;        /* Local use pointer */
  255.     if (fcb) {    
  256.     debug(F101,"zopeno fcb disp","",fcb->dsp);
  257.     debug(F101,"zopeno fcb type","",fcb->typ);
  258.     debug(F101,"zopeno fcb char","",fcb->cs);
  259.     } else {
  260.     debug(F100,"zopeno fcb is NULL","",0);
  261.     }
  262.     if (n != ZDFILE)
  263.       debug(F111," zopeno",name,n);
  264.     if (chkfn(n) != 0) return(0);
  265.     if ((n == ZCTERM) || (n == ZSTDIO)) {   /* Terminal or standard output */
  266.     fp[ZOFILE] = stdout;
  267.     debug(F101," fp[]=stdout", "", (int) fp[n]);
  268.     zoutcnt = 0;
  269.     zoutptr = zoutbuffer;
  270.     return(1);
  271.     }
  272.     p = "w";                /* Assume write/create mode */
  273.     if (fcb) {                /* If called with an FCB... */
  274.     if (fcb->dsp == XYFZ_A)        /* Does it say Append? */
  275.       p = "a";            /* Yes. */
  276.     }
  277.     fp[n] = fopen(name,p);        /* Open the file */
  278.  
  279.     if (fp[n] == NULL) {
  280.         perror("zopeno can't open");
  281.     } else {
  282.         if (n == ZDFILE) setbuf(fp[n],NULL); /* Debugging file unbuffered */
  283.     }
  284.     zoutcnt = 0;        /* (PWP) reset output buffer */
  285.     zoutptr = zoutbuffer;
  286.     if (n != ZDFILE)
  287.       debug(F101, " fp[n]", "", (int) fp[n]);
  288.     return((fp[n] != NULL) ? 1 : 0);
  289. }
  290.  
  291. /*  Z C L O S E  --  Close the given file.  */
  292.  
  293. /*  Returns 0 if arg out of range, 1 if successful, -1 if close failed.  */
  294. int 
  295. zclose(int n) {
  296.     int x, x2;
  297.  
  298.     if (chkfn(n) < 1) return(0);    /* Check range of n */
  299.  
  300.     if ((n == ZOFILE) && (zoutcnt > 0))    /* (PWP) output leftovers */
  301.       x2 = zoutdump();
  302.     else
  303.       x2 = 0;
  304.  
  305.     x = 0;                /* Initialize return code */
  306.     if (fp[ZSYSFN]) {            /* If file is realy a pipe */
  307.         x = zclosf(n);            /* do it specially */
  308.     } else {
  309.         if ((fp[n] != stdout) && (fp[n] != stdin)) x = fclose(fp[n]);
  310.     fp[n] = NULL;
  311.     }
  312.     iflen = -1;                /* Invalidate file length */
  313.     if (x == EOF)            /* if we got a close error */
  314.     return (-1);
  315.     else if (x2 < 0)        /* or an error flushing the last buffer */
  316.     return (-1);        /* then return an error */
  317.     else
  318.     return (1);
  319. }
  320.  
  321. /*  Z C H I N  --  Get a character from the input file.  */
  322.  
  323. /*  Returns -1 if EOF, 0 otherwise with character returned in argument  */
  324. int
  325. zchin(int n, int *c) {
  326.     int a, x;
  327.  
  328.     /* (PWP) Just in case this gets called when it shoudn't */
  329.     if (n == ZIFILE) {
  330.     x = zminchar();
  331.     *c = x;
  332.     return (x);
  333.     }
  334.  
  335.     /* if (chkfn(n) < 1) return(-1); */
  336.     a = getc(fp[n]);
  337.     if (a == EOF) return(-1);
  338.     *c = (CHAR) a & 0377;
  339.     return(0);
  340. }
  341.  
  342. /*  Z S I N L  --  Read a line from a file  */
  343.  
  344. /*
  345.   Writes the line into the address provided by the caller.
  346.   n is the Kermit "channel number".
  347.   Writing terminates when newline is encountered, newline is not copied.
  348.   Writing also terminates upon EOF or if length x is exhausted.
  349.   Returns 0 on success, -1 on EOF or error.
  350. */
  351. int
  352. zsinl(int n, char *s, int x) {
  353.     int z = 0, a;
  354.  
  355.     if (chkfn(n) < 1) {            /* Make sure file is open */
  356.     return(-1);
  357.     }
  358.     while (x--) {
  359.     if (zchin(n,&a) < 0) {        /* Read a character from the file */
  360.         z = -1;
  361.         break;
  362.     }
  363.     if (a == '\n') break;
  364.     *s = a;
  365.     s++;
  366.     }
  367.     *s = '\0';
  368.     return(z);
  369. }
  370.  
  371. /*
  372.  * (PWP) (re)fill the buffered input buffer with data.  All file input
  373.  * should go through this routine, usually by calling the zminchar()
  374.  * macro (in ckcker.h).
  375.  */
  376. int
  377. zinfill(void) {
  378.     zincnt = fread(zinbuffer, sizeof (char), INBUFSIZE, fp[ZIFILE]);
  379.     debug(F101,"zinfill zincnt","",zincnt);
  380.     if (zincnt == 0) return (-1); /* end of file */
  381.     zinptr = zinbuffer;       /* set pointer to beginning, (== &zinbuffer[0]) */
  382.     zincnt--;            /* one less char in buffer */
  383.     return((int)(*zinptr++) & 0377); /* because we return the first */
  384. }
  385.  
  386. /*  Z S O U T  --  Write a string to the given file, buffered.  */
  387. int
  388. zsout(int n, char *s) {
  389.     if (chkfn(n) < 1) return(-1);
  390.     fputs(s,fp[n]);
  391.     return(0);
  392. }
  393.  
  394. /*  Z S O U T L  --  Write string to file, with line terminator, buffered  */
  395. int
  396. zsoutl(int n, char *s) {
  397.     if (chkfn(n) < 1) return(-1);
  398.     fputs(s,fp[n]);
  399.     fputs("\n",fp[n]);
  400.     return(0);
  401. }
  402.  
  403. /*  Z S O U T X  --  Write x characters to file, unbuffered.  */
  404. int
  405. zsoutx(int n, char *s, int x) {
  406.     if (chkfn(n) < 1) return(-1);
  407.     return(write(fileno(fp[n]),s,x));
  408. }
  409.  
  410.  
  411. /*  Z C H O U T  --  Add a character to the given file.  */
  412.  
  413. /*  Should return 0 or greater on success, -1 on failure (e.g. disk full)  */
  414. int 
  415. zchout(int n, char c) {
  416.     if (chkfn(n) < 1) return(-1);
  417.     if (n == ZSFILE)
  418.         return(write(fileno(fp[n]),&c,1)); /* Use unbuffered for session log */
  419.     else {                /* Buffered for everything else */
  420.     if (putc(c,fp[n]) == EOF)    /* If true, maybe there was an error */
  421.         return(ferror(fp[n])?-1:0);    /* Check to make sure */
  422.     else                /* Otherwise... */
  423.         return(0);            /* There was no error. */
  424.     }
  425. }
  426.  
  427. /* (PWP) buffered character output routine to speed up file IO */
  428. int
  429. zoutdump(void) {
  430.     int x;
  431.     zoutptr = zoutbuffer;        /* reset buffer pointer in all cases */
  432.     debug(F101,"zoutdump chars","",zoutcnt);
  433.     if (zoutcnt == 0) {            /* nothing to output */
  434.     return(0);
  435.     } else if (zoutcnt < 0) {        /* unexpected negative value */
  436.     zoutcnt = 0;            /* reset output buffer count */
  437.     return(-1);            /* and fail. */
  438.     }
  439.     
  440. /* Frank Prindle suggested that replacing this fwrite() by an fflush() */
  441. /* followed by a write() would improve the efficiency, especially when */
  442. /* writing to stdout.  Subsequent tests showed a 5-fold improvement!   */
  443. /*  if (x = fwrite(zoutbuffer, 1, zoutcnt, fp[ZOFILE])) {              */
  444.  
  445.     fflush(fp[ZOFILE]);
  446.     if (x = write(fileno(fp[ZOFILE]),zoutbuffer,zoutcnt)) {
  447.     debug(F101,"zoutdump fwrite wrote","",x);
  448.     zoutcnt = 0;            /* reset output buffer count */
  449.     return(0);            /* things worked OK */
  450.     } else {
  451.     zoutcnt = 0;            /* reset output buffer count */
  452.     x = ferror(fp[ZOFILE]);        /* get error code */
  453.     debug(F101,"zoutdump fwrite error","",x);
  454.     return(x ? -1 : 0);        /* return failure if error */
  455.     }
  456. }
  457.  
  458. /*  C H K F N  --  Internal function to verify file number is ok  */
  459.  
  460. /*
  461.  Returns:
  462.   -1: File number n is out of range
  463.    0: n is in range, but file is not open
  464.    1: n in range and file is open
  465. */
  466. int
  467. chkfn(int n) {
  468.     switch (n) {
  469.     case ZCTERM:
  470.     case ZSTDIO:
  471.     case ZIFILE:
  472.     case ZOFILE:
  473.     case ZDFILE:
  474.     case ZTFILE:
  475.     case ZPFILE:
  476.     case ZSFILE:
  477.     case ZSYSFN:
  478.         case ZRFILE:
  479.         case ZWFILE: break;
  480.     default:
  481.         debug(F101,"chkfn: file number out of range","",n);
  482.         fprintf(stderr,"?File number out of range - %d\n",n);
  483.         return(-1);
  484.     }
  485.     return( (fp[n] == NULL) ? 0 : 1 );
  486. }
  487.  
  488. /*  Z C H K I  --  Check if input file exists and is readable  */
  489.  
  490. /*
  491.   Returns:
  492.    >= 0 if the file can be read (returns the size).
  493.      -1 if file doesn't exist or can't be accessed,
  494.      -2 if file exists but is not readable (e.g. a directory file).
  495.      -3 if file exists but protected against read access.
  496. */
  497. long
  498. zchki(char *name) {
  499.     long size, readstat();
  500.  
  501.     size = readstat(name);
  502.     debug(F111,"zchki file size",name,(int)size);
  503.     iflen = size;
  504.     strcpy(nambuf, name);        /* Remember file name globally. */
  505.     return(size);
  506. }
  507.  
  508. /*  Z C H K O  --  Check if output file can be created  */
  509.  
  510. /*
  511.  Returns -1 if write permission for the file would be denied, 0 otherwise.
  512. */
  513. int
  514. zchko(char *name) {
  515.     int rc = writestat(name);
  516.  
  517. #ifdef DEBUG
  518.     if (rc < 0)
  519.     debug(F111,"zchko access failed:",name,rc);
  520.     else
  521.     debug(F111,"zchko access ok:",name,rc);
  522. #endif
  523.     return(rc);
  524. }
  525.  
  526. /*  Z D E L E T  --  Delete the named file.  */
  527. int
  528. zdelet(char *name) {
  529.     return(unlink(name));
  530. }
  531.  
  532.  
  533. /*  Z R T O L  --  Convert remote filename into local form  */
  534.  
  535. /*  For AMIGA, this means changing uppercase letters to lowercase.  */
  536.  
  537. void
  538. zrtol(char *name, char *name2) {
  539.     for ( ; *name != '\0'; name++) {
  540.         *name2++ = isupper(*name) ? tolower(*name) : *name;
  541.     }
  542.     *name2 = '\0';
  543.     debug(F110,"zrtol:",name2,0);
  544. }
  545.  
  546. /*  Z S T R I P  --  Strip device & directory name from file specification */
  547.  
  548. /*  Strip pathname from filename "name", return pointer to result in name2 */
  549.  
  550. static char work[100];    /* buffer for use by zstrip and zltor */
  551.  
  552. void
  553. zstrip(char *name, char **name2) {
  554.     char *cp, *pp;
  555.     debug(F110,"zstrip before",name,0);
  556.     pp = work;
  557.     if ((cp = strrchr(name, ':')) == NULL)
  558.         cp = name;
  559.     else
  560.         ++cp;
  561.     for (; *cp != '\0'; cp++) {
  562.         if (*cp == '/')
  563.       pp = work;
  564.     else
  565.       *pp++ = *cp;
  566.     }
  567.     *pp = '\0';                /* Terminate the string */
  568.     *name2 = work;
  569.     debug(F110,"zstrip after",*name2,0);
  570. }
  571.  
  572. /*  Z L T O R  --  Local TO Remote */
  573.  
  574. /*  Convert filename from local format to common (remote) form.  */
  575.  
  576. void
  577. zltor(char *name, char *name2) {
  578.     char *cp, *pp;
  579.     int dc = 0;
  580.  
  581.     debug(F110,"zltor",name,0);
  582.     pp = work;
  583.     if ((cp = strrchr(name, ':')) == NULL)
  584.         cp = name;
  585.     else
  586.         ++cp;
  587.  
  588.     for (; *cp != '\0'; cp++) {    /* strip path name */
  589.         if (*cp == '/') {
  590.         dc = 0;
  591.         pp = work;
  592.     }
  593.     else if (islower(*cp)) *pp++ = toupper(*cp); /* Uppercase letters */
  594.     else if (*cp == '~') *pp++ = 'X';    /* Change tilde to 'X' */
  595.     else if (*cp == '#') *pp++ = 'X';    /* Change number sign to 'X' */
  596.     else if ((*cp == '.') && (++dc > 1)) *pp++ = 'X'; /* & extra dots */
  597.     else *pp++ = *cp;
  598.     }
  599.     *pp = '\0';                /* Tie it off. */
  600.     cp = name2;                /* If nothing before dot, */
  601.     if (*work == '.') *cp++ = 'X';    /* insert 'X' */
  602.     strcpy(cp,work);
  603.     debug(F110," name2",name2,0);
  604. }    
  605.  
  606. /*  Z H O M E  --  Return pointer to user's home directory  */
  607.  
  608. /* we return "s:", which is where startup scripts are found */
  609. char *
  610. zhome(void) {
  611.     return("s:");        /* very approximately */
  612. }
  613.  
  614. /*  Z C H D I R  --  Change directory  */
  615. int
  616. zchdir(char *dirnam) {
  617.     if (chdir(dirnam) != 0)        /* failed */
  618.         return 0;
  619.     if (v37)                /* This only if V37 or more */
  620.         if (!SetCurrentDirName(dirnam))
  621.             return 0;
  622.     return 1;
  623. }
  624.  
  625. /*  Z G T D I R  --  Return pointer to user's current directory  */
  626.  
  627. char *
  628. zgtdir(void) {
  629.  
  630. #ifdef MAXPATHLEN
  631. #define CWDBL MAXPATHLEN
  632. #else
  633. #define CWDBL 100
  634. #endif
  635.  
  636.     static char cwdbuf[CWDBL+1];
  637.     char *buf, *getcwd();
  638.     buf = cwdbuf;
  639.     return(getcwd(buf, CWDBL));
  640. }
  641.  
  642. /*  Z X C M D -- Run a system command so its output can be read like a file */
  643. int
  644. zxcmd(int filnum, char *comand) {
  645.     FILE *pipeopen();
  646.     int out;
  647.  
  648.     if (chkfn(filnum) < 0) return(-1);    /* Need a valid Kermit file number. */
  649.     if (filnum == ZSTDIO || filnum == ZCTERM) /* But not one of these. */
  650.       return(0);
  651.  
  652.     out = (filnum == ZIFILE || filnum == ZRFILE) ? 0 : 1 ;
  653.  
  654. /* Output to a command */
  655.  
  656.     if (out) {                /* Need popen() to do this. */
  657.         return -1;            /* Not yet supported. */
  658.     }
  659.  
  660. /* Input from a command */
  661.     else {
  662.     if ((fp[filnum] = pipeopen(comand)) == NULL) return -1;
  663.     fp[ZSYSFN] = fp[filnum];    /* Remember */ 
  664.     zincnt = 0;            /* (PWP) reset input buffer */
  665.     zinptr = zinbuffer;
  666.     }
  667.     return 1;
  668. }
  669.  
  670. /*  Z C L O S F  - wait for the child fork to terminate and close the pipe. */
  671. int
  672. zclosf(int filnum) {
  673.     pipeclose(fp[filnum]);
  674.     fp[filnum] = fp[ZSYSFN] = NULL;
  675.     return(1);
  676. }
  677.  
  678. /*  Z X P A N D  --  Expand a wildcard string into an array of strings  */
  679. /*
  680.   Returns the number of files that match fn1, with data structures set up
  681.   so that first file (if any) will be returned by the next znext() call.
  682. */
  683. int
  684. zxpand(char *fn) {
  685.     fcount = fgen(fn,mtchs,MAXWLD);    /* Look up the file. */
  686.     if (fcount > 0) {
  687.     mtchptr = mtchs;        /* Save pointer for next. */
  688.     }
  689.     debug(F111,"zxpand",mtchs[0],fcount);
  690.     return(fcount);
  691. }
  692.  
  693.  
  694. /*  Z N E X T  --  Get name of next file from list created by zxpand(). */
  695. /*
  696.  Returns >0 if there's another file, with its name copied into the arg string,
  697.  or 0 if no more files in list.
  698. */
  699. int
  700. znext(char *fn) {
  701.     if (fcount-- > 0) strcpy(fn,*mtchptr++);
  702.     else *fn = '\0';
  703.     debug(F111,"znext",fn,fcount+1);
  704.     return(fcount+1);
  705. }
  706.  
  707. /*  Z C H K S P A -- Check to see if there is enough space for the file. */
  708.  
  709. /*
  710.  * Uses Manx-supplied dospacket() routine. (Source supplied for SAS/C
  711.  *                                            by Larry Rosenman)
  712.  */
  713. int
  714. zchkspa(char *fn, long len) {
  715.     struct MsgPort *MyPort;
  716.     struct InfoData *MyInfo;
  717.     long space;
  718.  
  719.     if ((MyPort = (struct MsgPort *)DeviceProc(fn)) == NULL)
  720.     return -1;
  721.     if ((MyInfo = AllocMem(sizeof(struct InfoData), MEMF_PUBLIC)) == NULL)
  722.     return -1;
  723.     if (dos_packet(MyPort, ACTION_DISK_INFO, ((BPTR) MyInfo) >> 2,
  724.                    0L, 0L, 0L, 0L, 0L) != 0) {
  725.     if (MyInfo->id_UnitNumber == -1)    /* Imperfect check for RAM: */
  726.         space = len + 1;            /* Always enough space */
  727.     else
  728.         space = (MyInfo->id_NumBlocks - MyInfo->id_NumBlocksUsed)*
  729.                     MyInfo->id_BytesPerBlock;
  730.     } else
  731.     space = -1;        /* To mark error return after FreeMem(). */
  732.     FreeMem(MyInfo, sizeof(struct InfoData));
  733.     if (space <= 0)
  734.     return -1;
  735.     else if (len < space)
  736.     return 1;
  737.     else
  738.     return 0;
  739. }
  740.  
  741. /*  Z N E W N  --  Make a new name for the given file  */
  742.  
  743. void
  744. znewn(char *fn,char **s) {
  745.     static char buf[100];
  746.     char *bp;
  747.     int len = 0, d;
  748. #ifdef MAXNAMLEN    
  749.     int maxlen = MAXNAMLEN;
  750. #else
  751.     int maxlen = 14;
  752. #endif
  753.  
  754.     bp = buf;
  755.     while (*fn) {            /* Copy name into buf */
  756.     *bp++ = *fn++;
  757.     len++;
  758.     }
  759.     if (len > maxlen-3) bp -= 3;    /* Don't let it get too long */
  760.  
  761.     /* 
  762.      * On the Amiga, it takes much less time to determine
  763.      * if a given file exists than to read all the file names in
  764.      * a directory (or even just names with a certain prefix).
  765.      */
  766.     d = 0;
  767.     do {
  768.     sprintf(bp, "~%d", ++d);
  769.     } while (zchki(buf) != -1 && d < 100);
  770.  
  771.     *s = buf;
  772. }
  773.  
  774. /*  Z S A T T R */
  775. /*
  776.  Fills in a Kermit file attribute structure for the file which is to be sent.
  777.  Returns 0 on success with the structure filled in, or -1 on failure.
  778.  If any string member is null, then it should be ignored.
  779.  If any numeric member is -1, then it should be ignored.
  780. */
  781. int
  782. zsattr(struct zattr *xx) {
  783.     long k;
  784.     char *zfcdat();
  785.  
  786.     k = iflen % 1024L;            /* File length in K */
  787.     if (k != 0L) k = 1L;
  788.     xx->lengthk = (iflen / 1024L) + k;
  789.     xx->type.len = 0;            /* File type can't be filled in here */
  790.     xx->type.val = "";
  791.     if (*nambuf) {
  792.     xx->date.val = zfcdat(nambuf);    /* File creation date */
  793.     xx->date.len = strlen(xx->date.val);
  794.     } else {
  795.     xx->date.len = 0;
  796.     xx->date.val = "";
  797.     }
  798.     xx->creator.len = 0;        /* File creator */
  799.     xx->creator.val = "";
  800.     xx->account.len = 0;        /* File account */
  801.     xx->account.val = "";
  802.     xx->area.len = 0;            /* File area */
  803.     xx->area.val = "";
  804.     xx->passwd.len = 0;            /* Area password */
  805.     xx->passwd.val = "";
  806.     xx->blksize = -1L;            /* File blocksize */
  807.     xx->access.len = 0;            /* File access */
  808.     xx->access.val = "";
  809.     xx->encoding.len = 0;        /* Transfer syntax */
  810.     xx->encoding.val = 0;
  811.     xx->disp.len = 0;            /* Disposition upon arrival */
  812.     xx->disp.val = "";
  813.     xx->lprotect.len = 0;        /* Local protection */
  814.     xx->lprotect.val = "";
  815.     xx->gprotect.len = 0;        /* Generic protection */
  816.     xx->gprotect.val = "";
  817.     xx->systemid.len = 2;        /* System ID length */
  818.     xx->systemid.val = "L3";        /* Amiga system ID code */
  819.     xx->recfm.len = 0;            /* Record format */
  820.     xx->recfm.val = "";
  821.     xx->sysparam.len = 0;        /* System-dependent parameters */
  822.     xx->sysparam.val = "";
  823.     xx->length = iflen;            /* Length */
  824.     return(0);
  825. }
  826.  
  827. /* Z F C D A T -- Return a string containing the time stamp for a file */
  828.  
  829. char *
  830. zfcdat(char *name) {
  831.  
  832.     struct stat buffer;
  833.     struct tm *time_stamp, *localtime();
  834.     time_t filetime;
  835.     static char datbuf[20];
  836.  
  837.     datbuf[0] = '\0';
  838.     if(stat(name,&buffer) != 0) {
  839.     debug(F110,"zcfdat stat failed",name,0);
  840.     return("");
  841.     }
  842.     filetime = StatToTime(buffer.st_mtime);
  843.     time_stamp = localtime(&filetime);
  844.     if (time_stamp->tm_year < 1900) time_stamp->tm_year += 1900;
  845.     sprintf(datbuf,"%-4.4d%02.2d%02.2d %002.2d:%002.2d:%002.2d",
  846.         time_stamp->tm_year,
  847.         time_stamp->tm_mon + 1,
  848.         time_stamp->tm_mday,
  849.         time_stamp->tm_hour,
  850.         time_stamp->tm_min,
  851.         time_stamp->tm_sec);
  852.     debug(F111,"zcfdat",datbuf,strlen(datbuf));
  853.     return(datbuf);
  854. }
  855.  
  856. /* Z S T I M E  --  Set creation date for incoming file */
  857. /*
  858.  Call with:
  859.  f  = pointer to name of existing file.
  860.  yy = pointer to a Kermit file attribute structure in which yy->date.val
  861.       is a date of the form yyyymmdd hh:mm:ss, e.g. 19900208 13:00:00.
  862.  x  = is a function code: 0 means to set the file's creation date as given.
  863.       1 means compare the given date with the file creation date.      
  864.  Returns:
  865.  -1 on any kind of error.
  866.   0 if x is 0 and the file date was set successfully.
  867.   0 if x is 1 and date from attribute structure <= file creation date.
  868.   1 if x is 1 and date from attribute structure > file creation date.
  869. */
  870. int
  871. zstime(char *f, struct zattr *yy, int x) {
  872.  
  873. /*
  874.  * This code takes advantage of the ANSI time functions.  Once UNIX has
  875.  * an ANSI compiler, maybe UNIX can use this one instead...
  876.  */
  877.  
  878.     struct tm InTime;
  879.     time_t CompareTime;
  880.     struct stat MyStat;
  881.     
  882.     int isleapyear, i;
  883.     static int monthdays[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
  884.  
  885.     debug(F110,"zstime",f,0);
  886.  
  887.     if (sscanf(yy->date.val, "%4d%2d%2d %2d:%2d:%2d", &InTime.tm_year,
  888.            &InTime.tm_mon, &InTime.tm_mday, &InTime.tm_hour,
  889.            &InTime.tm_min, &InTime.tm_sec) != 6) {
  890.     debug(F111, "Bad creation date ", yy->date.val, yy->date.len);
  891.     return -1;
  892.     }
  893.     InTime.tm_mon--;        /* a struct tm contains months with 0 = Jan */
  894.  
  895.     isleapyear = (( InTime.tm_year % 4 == 0 && InTime.tm_year % 100 !=0) ||
  896.                   InTime.tm_year % 400 == 0);
  897.     InTime.tm_year -= 1900;
  898. /*
  899.  * Find number of days since start-of-year.
  900.  */
  901.     InTime.tm_yday = (isleapyear ? 0 : 1);
  902.     for (i = 0; i <= InTime.tm_mon; i++)
  903. /*    InTime.tm_yday += monthdays[0]; */ /*ler*/
  904.     InTime.tm_yday += monthdays[i]; 
  905.     InTime.tm_yday += InTime.tm_mday;
  906.     InTime.tm_isdst = 0;        /* No daylight savings on Amiga. */
  907. /*
  908.  * We don't set day-of-week in this code, and simply hope mktime ignores it.
  909.  */
  910.     CompareTime = mktime(&InTime);
  911.     if (x == 1) {            /* Compare time with file */
  912.     if (stat(f, &MyStat) < 0) {
  913.         debug(F110,"zstime: stat failed", f, 0);
  914.         return -1;
  915.     }
  916.     if (StatToTime(MyStat.st_mtime) <= CompareTime)
  917.         return 0;
  918.     else
  919.         return 1;
  920.     } else if (x == 0) {        /* Set file to time */
  921.     struct DateStamp NewTime;
  922.  
  923.     TimeToDateStamp(CompareTime, &NewTime);
  924.     return(touch(f, &NewTime));
  925.     }
  926.     return -1;                /* Illegal value for x */
  927. }
  928. /*
  929.  * Set modification date of file fn to NewTime.
  930.  */
  931. static int
  932. touch(char *fn, struct DateStamp *NewTime) {
  933.     struct MsgPort *task;
  934.     BPTR lock, plock;
  935.     UBYTE *pointer;
  936.  
  937.     if(!(pointer = (UBYTE *)AllocMem(256L,MEMF_PUBLIC)))
  938.     return -1;
  939.     if(!(task=(struct MsgPort *)DeviceProc(fn))) {
  940.     FreeMem((void *) pointer, 256L);
  941.     return;
  942.     }
  943.     if(!(lock = Lock(fn,SHARED_LOCK))) {
  944.     FreeMem((void *) pointer, 256L);
  945.     return -1;
  946.     }
  947.     plock = ParentDir(lock);
  948.     UnLock(lock);
  949.  
  950.     strcpy((char *)(pointer + 1),fn);
  951.     *pointer = strlen(fn);
  952.  
  953.     dos_packet(task, ACTION_SET_DATE, NULL, plock, (ULONG) &pointer[0] >> 2,
  954.     (ULONG) NewTime, 0L, 0L, 0L);
  955.  
  956.     UnLock(plock);
  957.     FreeMem((void *) pointer, 256L);
  958.     return 0;
  959. }
  960. /*
  961.  * Dummy functions for the Amiga.  Sending mail cannot be done;  I haven't
  962.  * decided how to handle print requests yet.
  963.  */
  964. int
  965. zmail(char *p, char *f) {        /* Send file f as mail to address p */
  966.     return(0);
  967. }
  968.  
  969. int
  970. zprint(char *p, char *f) {        /* Print file f with flags p */
  971.     return(0);
  972. }
  973.  
  974. int
  975. zrename(char *old, char *new) {
  976.     return(rename(old, new) == 0 ? 0 : -1);
  977. }
  978.  
  979. /* Z S H C M D -- Issue shell command and redirect output, if necessary. */
  980.  
  981. /*
  982.  * This function is to pass the command contained in the string s to the
  983.  * local command parser.  If the command does not begin with the character
  984.  * ">", then give the command to the system and display its results on the
  985.  * screen.  If the command does not begin with ">" and local != 0, then send
  986.  * the results of the command out the currently open communications device.
  987.  *
  988.  * In this version, we simply punt.
  989.  */
  990. int
  991. zshcmd(char *s) {
  992.     if (*s == '>') s++;
  993.     return(system(s));
  994. }
  995.  
  996. /* Directory Functions for Unix, written by Jeff Damens, CUCCA, 1984. */
  997.  
  998. /*
  999.  * The path structure is used to represent the name to match.
  1000.  * Each slash-separated segment of the name is kept in one
  1001.  * such structure, and they are linked together, to make
  1002.  * traversing the name easier.
  1003.  */
  1004.  
  1005. struct path {
  1006.               char npart[MAXNAMLEN];    /* name part of path segment */
  1007.               struct path *fwd;        /* forward ptr */
  1008.             };
  1009.  
  1010. #define SSPACE 4000            /* size of string-generating buffer */
  1011.  
  1012. static char sspace[SSPACE];             /* buffer to generate names in */
  1013. static char *freeptr,**resptr;             /* copies of caller's arguments */
  1014. static int remlen;                      /* remaining length in caller's array*/
  1015. static int numfnd;                      /* number of matches found */
  1016.  
  1017. /*
  1018.  * splitpath:
  1019.  *  takes a string and splits the slash-separated portions into
  1020.  *  a list of path structures.  Returns the head of the list.  The
  1021.  *  structures are allocated by malloc, so they must be freed.
  1022.  *  Splitpath is used internally by the filename generator.
  1023.  *
  1024.  * Input: A string.
  1025.  * Returns: A linked list of the slash-separated segments of the input.
  1026.  */
  1027.  
  1028. struct path *
  1029. splitpath(char *p) {
  1030.  struct path *head,*cur,*prv;
  1031.  int i;
  1032.  head = prv = NULL;
  1033.  if (*p == '/') p++;            /* skip leading slash */
  1034.  while (*p != '\0')
  1035.  {
  1036.    cur = (struct path *) malloc(sizeof (struct path));
  1037.    debug(F101,"splitpath malloc","",(cur == NULL ? 0 : 1));
  1038.    if (cur == NULL) fatal("malloc fails in splitpath()");
  1039.    cur -> fwd = NULL;
  1040.    if (head == NULL) head = cur;
  1041.    else prv -> fwd = cur;       /* link into chain */
  1042.    prv = cur;
  1043.    for (i=0; i < MAXNAMLEN && *p != '/' && *p != '\0'; i++)
  1044.      cur -> npart[i] = *p++;
  1045.    cur -> npart[i] = '\0';      /* end this segment */
  1046.    if (i >= MAXNAMLEN) while (*p != '/' && *p != '\0') p++;
  1047.    if (*p == '/') p++;
  1048.  }
  1049.  return(head);
  1050. }
  1051.  
  1052. /*
  1053.  * fgen:
  1054.  *  This is the actual name generator.  It is passed a string,
  1055.  *  possibly containing wildcards, and an array of character pointers.
  1056.  *  It finds all the matching filenames and stores them into the array.
  1057.  *  The returned strings are allocated from a static buffer local to
  1058.  *  this module (so the caller doesn't have to worry about deallocating
  1059.  *  them); this means that successive calls to fgen will wipe out
  1060.  *  the results of previous calls.  This isn't a problem here
  1061.  *  because we process one wildcard string at a time.
  1062.  *
  1063.  * Input: a wildcard string, an array to write names to, the
  1064.  *        length of the array.
  1065.  * Returns: the number of matches.  The array is filled with filenames
  1066.  *          that matched the pattern.  If there wasn't enough room in the
  1067.  *        array, -1 is returned.
  1068.  * By: Jeff Damens, CUCCA, 1984.
  1069.  */
  1070. int
  1071. fgen(char *pat, char *resarry[], int len) {
  1072.  struct path *head;
  1073.  char scratch[100],*sptr;
  1074.  char *tail;
  1075.  void traverse(struct path *pl, char *sofar, char *endcur);
  1076.  
  1077.  if ((tail = strrchr(pat, ':')) == NULL) /* locate unit name */
  1078.   tail = pat;                /* no unit name */
  1079.  else
  1080.   ++tail;                /* eat ':' */
  1081.  while (*tail == '/')            /* eat parent path slashes */
  1082.   ++tail;
  1083.  sptr = scratch;            /* init buffer correctly */
  1084.  while (pat < tail)
  1085.   *sptr++ = *pat++;
  1086.  head = splitpath(pat);
  1087.  numfnd = 0;                            /* none found yet */
  1088.  freeptr = sspace;            /* this is where matches are copied */
  1089.  resptr = resarry;            /* static copies of these so*/
  1090.  remlen = len;                /* recursive calls can alter them */
  1091.  traverse(head,scratch,sptr);        /* go walk the directory tree */
  1092.  while (head != NULL) {
  1093.    struct path *next = head -> fwd;
  1094.    free(head);                /* return the path segments */
  1095.    head = next;
  1096.  }
  1097.  return(numfnd);            /* and return the number of matches */
  1098. }
  1099.  
  1100. /* traverse:
  1101.  *  Walks the directory tree looking for matches to its arguments.
  1102.  *  The algorithm is, briefly:
  1103.  *   If the current pattern segment contains no wildcards, that
  1104.  *   segment is added to what we already have.  If the name so far
  1105.  *   exists, we call ourselves recursively with the next segment
  1106.  *   in the pattern string; otherwise, we just return.
  1107.  *
  1108.  *   If the current pattern segment contains wildcards, we open the name
  1109.  *   we've accumulated so far (assuming it is really a directory), then read 
  1110.  *   each filename in it, and, if it matches the wildcard pattern segment, add
  1111.  *   that filename to what we have so far and call ourselves recursively on the
  1112.  *   next segment.
  1113.  *
  1114.  *   Finally, when no more pattern segments remain, we add what's accumulated
  1115.  *   so far to the result array and increment the number of matches.
  1116.  *
  1117.  * Input: a pattern path list (as generated by splitpath), a string
  1118.  *      pointer that points to what we've traversed so far (this
  1119.  *      can be initialized to "/" to start the search at the root
  1120.  *      directory, or to "./" to start the search at the current
  1121.  *      directory), and a string pointer to the end of the string
  1122.  *      in the previous argument.
  1123.  * Returns: nothing.
  1124.  */
  1125. void
  1126. traverse(struct path *pl, char *sofar, char *endcur) {
  1127.  struct DirHandle *fd;
  1128.  char *fname;
  1129.  
  1130.  if (pl == NULL)
  1131.  {
  1132.   *--endcur = '\0';                    /* end string, overwrite trailing / */
  1133.   addresult(sofar);
  1134.   return;
  1135.  }
  1136.  if (!iswild(pl -> npart))
  1137.  {
  1138.   strcpy(endcur,pl -> npart);
  1139.   endcur += strlen(pl -> npart);
  1140.   *endcur = '\0';                         /* end current string */
  1141.   if (existobj(sofar))            /* if current piece exists */
  1142.   {
  1143.       *endcur++ = '/';            /* add slash to end */
  1144.       *endcur = '\0';            /* and end the string */
  1145.       traverse(pl -> fwd,sofar,endcur);
  1146.   }
  1147.   return;
  1148.  }
  1149. /* cont'd... */
  1150.  
  1151. /*...traverse, cont'd */
  1152.  
  1153. /* segment contains wildcards, have to search directory */
  1154.  *endcur = '\0';                            /* end current string */
  1155.  if ((fd = opendir(sofar)) == NULL) return;      /* can't open, forget it */
  1156.  while (fname = readdir(fd))
  1157. {
  1158.   if (match(pl -> npart,fname)) {
  1159.     char *eos;
  1160.     strcpy(endcur,fname);
  1161.     eos = endcur + strlen(fname);
  1162.     *eos = '/';                    /* end this segment */
  1163.     traverse(pl -> fwd,sofar,eos+1);
  1164.   }
  1165. }
  1166.  closedir(fd);
  1167. }
  1168.  
  1169. /*
  1170.  * addresult:
  1171.  *  Adds a result string to the result array.  Increments the number
  1172.  *  of matches found, copies the found string into our string
  1173.  *  buffer, and puts a pointer to the buffer into the caller's result
  1174.  *  array.  Our free buffer pointer is updated.  If there is no
  1175.  *  more room in the caller's array, the number of matches is set to -1.
  1176.  * Input: a result string.
  1177.  * Returns: nothing.
  1178.  */
  1179. int
  1180. addresult(char *str) {
  1181.  int l;
  1182.  if (--remlen < 0) {
  1183.   numfnd = -1;
  1184.   return;
  1185.  }
  1186.  l = strlen(str) + 1;            /* size this will take up */
  1187.  if ((freeptr + l) > &sspace[SSPACE]) {
  1188.     numfnd = -1;            /* do not record if not enough space */
  1189.     return;
  1190.   }
  1191.  strcpy(freeptr,str);
  1192.  *resptr++ = freeptr;
  1193.  freeptr += l;
  1194.  numfnd++;
  1195. }
  1196.  
  1197. int 
  1198. iswild(char *str) {
  1199.  char c;
  1200.  while ((c = *str++) != '\0')
  1201.    if (c == '*' || c == '?') return(1);
  1202.  return(0);
  1203. }
  1204.  
  1205. #ifdef OLDMATCH
  1206. /*
  1207.  * match:
  1208.  *  pattern matcher.  Takes a string and a pattern possibly containing
  1209.  *  the wildcard characters '*' and '?'.  Returns true if the pattern
  1210.  *  matches the string, false otherwise.
  1211.  * by: Jeff Damens, CUCCA
  1212.  *
  1213.  * Input: a string and a wildcard pattern.
  1214.  * Returns: 1 if match, 0 if no match.
  1215.  */
  1216. int
  1217. match(char *pattern, char *string) {
  1218.     char *psave,*ssave;            /* back up pointers for failure */
  1219.     psave = ssave = NULL;
  1220.     while (1) {
  1221.     for (;
  1222.          tolower(*pattern) == tolower(*string);
  1223.          pattern++,string++)  /* skip first */
  1224.         if (*string == '\0') return(1);    /* end of strings, succeed */
  1225.     if (*string != '\0' && *pattern == '?') {
  1226.         pattern++;            /* '?', let it match */
  1227.         string++;
  1228.     } else if (*pattern == '*') {    /* '*' ... */
  1229.         psave = ++pattern;        /* remember where we saw it */
  1230.         ssave = string;        /* let it match 0 chars */
  1231.     } else if (ssave != NULL && *ssave != '\0') {    /* if not at end  */
  1232.                       /* ...have seen a star */
  1233.         string = ++ssave;        /* skip 1 char from string */
  1234.         pattern = psave;        /* and back up pattern */
  1235.     } else return(0);        /* otherwise just fail */
  1236.     }
  1237. }
  1238. #else
  1239. /*
  1240.  * match -- match wildcard pattern to string
  1241.  *    allows multiple '*'s and works without backtracking
  1242.  *    upper and lower case considered equivalent
  1243.  *    written by Jack Rouse
  1244.  *    working without backtracking is cute, but is this usually going
  1245.  *       to be the most efficient method?
  1246.  */
  1247. int
  1248. match(char *pattern, char *target) {
  1249.     int link[MAXNAMLEN];        /* list of matches to try in pattern */
  1250.     register int first, last;    /* first and last items in list */
  1251.     register int here, next;    /* current and next list items */
  1252.     char lowch;            /* current target character */
  1253.  
  1254.     /* start out trying to match at first position */
  1255.     first = last = 0;
  1256.     link[0] = -1;
  1257.  
  1258.     /* go through the target */
  1259.     for (; *target; ++target)
  1260.     {
  1261.         /* get lowercase target character */
  1262.         lowch = tolower(*target);
  1263.  
  1264.         /* go through all positions this round and build next round */
  1265.         last = next = -1;
  1266.         for (here = first; here >= 0; here = next)
  1267.         {
  1268.             next = link[here];
  1269.             switch (pattern[here])
  1270.             {
  1271.             case '*':
  1272.                 /* try match at here+1 this round */
  1273.                 /*!!!check needed only if "**" allowed? */
  1274.                 if (next != here + 1)
  1275.                 {
  1276.                     link[here + 1] = next;
  1277.                     next = here + 1;
  1278.                 }
  1279.                 /* retry match at here next round */
  1280.                 break;
  1281.             default:
  1282.                 if (tolower(pattern[here]) != lowch)
  1283.                     continue;
  1284.                 /* matched, fall through */
  1285.             case '?':
  1286.                 /* try match at here+1 next round */
  1287.                 ++here;
  1288.                 break;
  1289.             }
  1290.             /* try match at here value next round */
  1291.             if (last < 0)
  1292.                 first = here;
  1293.             else
  1294.                 link[last] = here;
  1295.             last = here;
  1296.         }
  1297.         /* if no positions left, match failed */
  1298.         if (last == -1) return(0);
  1299.         /* terminate list */
  1300.         link[last] = -1;
  1301.     }
  1302.  
  1303.     /* at end of target, skip empty matches */
  1304.     while (pattern[last] == '*')
  1305.         ++last;
  1306.  
  1307.     return(pattern[last] == '\0');
  1308. }
  1309. #endif
  1310.